package com.example.android.myapp.asyn;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.WindowManager;

/**
 * 可取消的等待框AsynTask
 * 
 * @author zhifeili 2012-3-29 下午4:15:54
 * 
 * @param <Params>
 * @param <Progress>
 * @param <Result>
 */
public abstract class DialogTask<Params, Progress, Result> extends BetterAsyncTask<Params, Progress, Result> implements
		DialogInterface.OnCancelListener {

	private Context mContext;

	private ProgressDialog mProgressDialog;

	/**
	 * 按Back键即可取消的Task
	 * 
	 * @param context
	 */
	public DialogTask(Context context) {
		this(context, true, true);
	}

	/**
	 * 如果cancelable传入false，则按Back键也不能取消
	 * 
	 * @param context
	 * @param cancelable
	 */
	public DialogTask(Context context, boolean showdialog, boolean cancelable) {
		super(context);
		mContext = context;
		if (showdialog) {
			mProgressDialog = new ProgressDialog(mContext);
			mProgressDialog.setCancelable(cancelable);
			if (cancelable) {
				mProgressDialog.setOnCancelListener(this);
			}
		}
	}

	public void setMessage(CharSequence message) {
		if (null != mProgressDialog) {
			mProgressDialog.setMessage(message);
		}
	}

	@Override
	protected void before(Context context) {
		if (null != mProgressDialog) {
			mProgressDialog.show();
			mProgressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
		}
	}

	@Override
	protected void after(Context context, Result result) {
		if (null != mProgressDialog) {
			mProgressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION);
			mProgressDialog.dismiss();
		}
	};

	@Override
	protected void onCancelled() {
		super.onCancelled();
		if (null != mProgressDialog && mProgressDialog.isShowing()) {
			mProgressDialog.dismiss();
		}
	}

	@Override
	public void onCancel(DialogInterface dialog) {
		cancel(true);
	}
}